package com.nowcoder.controller;

import com.nowcoder.model.User;
import com.nowcoder.service.ToutiaoService;
import com.nowcoder.service.UserService;
import com.nowcoder.utils.ToutiaoUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * Created by nowcoder on 2016/6/26.
 */
@Controller
public class LoginController {
    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    UserService userService;

    @RequestMapping(path={"/reg"},method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public String reg(Model model, @RequestParam(value = "username") String username,
                    @RequestParam(value="password") String password,
                    @RequestParam(value = "remember" ,defaultValue="0") int rememberme,
                    HttpServletResponse response) {

         try{
             Map<String,Object> map = userService.register(username,password);
             if(map.containsKey("ticket")) {
                 Cookie cookie = new Cookie("ticket",map.get("ticket").toString());
                 if(rememberme>0) {
                     cookie.setMaxAge(1000*3600*24);
                 }
                 cookie.setPath("/");
                 response.addCookie(cookie);
                 return ToutiaoUtil.getJSONString(0,"注册成功！");
             }
             return ToutiaoUtil.getJSONString(1,map);
         } catch(Exception e) {
             logger.error("regist error!"+e.getMessage());
             return ToutiaoUtil.getJSONString(1,"注册异常！");
         }
    }

}
